package com.yuchengtech.simpleServer.core.handler;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;

import sun.net.www.protocol.http.HttpURLConnection;

import com.yuchengtech.fileUtil.FileIo;
import com.yuchengtech.simpleServer.core.HttpRequest;
import com.yuchengtech.simpleServer.core.HttpResponse;
import com.yuchengtech.simpleServer.core.SimpleHttpServer;
import com.yuchengtech.simpleServer.jdv.JdvConfig;
import com.yuchengtech.simpleServer.jdv.JdvFile;
import com.yuchengtech.simpleServer.jdv.JdvUtil;


public class JdvHandler implements Handler{

	private static final JdvHandler JDV_HANDLER=new JdvHandler();
	
	
	private JdvHandler(){}
	
	public void doHandle(Socket connection, HttpRequest request,
			HttpResponse response) {
		
		String fileDir=request.getUrl();
		if(fileDir.startsWith("/"));
			fileDir=fileDir.substring(1);
		String basePath=SimpleHttpServer.getBasePath();
		File file=new File(basePath,fileDir);
		if(!file.exists()||!file.isFile())
		{
			response.setStatusCode(HttpURLConnection.HTTP_NOT_FOUND);
			try {
				response.doResponse();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return;	
		}
		if(file.length()!=0)
		{
		StringBuilder builder=FileIo.readFileAsStringBuilder(file,"utf-8");
		JdvConfig config=JdvConfig.getSingleJdvConfig();
		JdvFile jdvFile=config.getJdvFile(fileDir);
		if(jdvFile==null) //重新解析
		{
			jdvFile=new JdvFile();
			jdvFile.setFilePath(fileDir);
			jdvFile.setLastModified(file.lastModified());
			JdvUtil.parseJdvMark(jdvFile, builder);
			config.setJdvFile(jdvFile);
		}else if(jdvFile.getLastModified()!=file.lastModified())
		{
			jdvFile.setLastModified(file.lastModified());
			JdvUtil.parseJdvMark(jdvFile, builder);
		}
		
		String content=JdvUtil.parseJdvContent(request, jdvFile, builder);
		PrintWriter out=response.getPrintWriter();
		out.print(content);
		}
		
		try {
			response.doResponse();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	
	 public static JdvHandler getSingleHandler()
	  {
		return JDV_HANDLER;
	  }
	
}
